package mysql

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"sync"
	"zeroOne/goods_srv/app_config"
)

var (
	Db   *gorm.DB
	err  error
	once sync.Once
)

// 初始化连接数据库

func InitMysqlDb() {
	mysqlConf := app_config.AppConf.MySQLConfig
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", mysqlConf.User, mysqlConf.Password, mysqlConf.Host, mysqlConf.Port, mysqlConf.Database)
	once.Do(func() {
		Db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	})
	if err != nil {
		fmt.Println("mysql连接失败：", err)
		return
	}
	fmt.Println("mysql连接OK")

	// 数据迁移
	Db.AutoMigrate(new(Goods))
}
